//RequestMethodTest.java
package com.ylaihui.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

public class RequestMethodTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取资源路径
        String uri = req.getRequestURI();
        System.out.println(uri);  // /06_Servlet/requestMethodTest

        System.out.println(req.getRequestURL());  // http://localhost:8080/06_Servlet/requestMethodTest

        System.out.println(req.getRemoteHost());  //  127.0.0.1
        //  text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
        System.out.println(req.getHeader("Accept"));

        System.out.println(req.getMethod());  // GET

        System.out.println("***********getParameter***********");
        System.out.println(req.getParameter("username"));
        System.out.println(req.getParameter("passwd"));
        String[] insts = req.getParameterValues("inst");

        for (int i = 0; i <insts.length; i++) {
            System.out.println(insts[i]);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getMethod());  // POST

        // 如果 username 为 汉字时， 会显示乱码， 这里设置下字符集，避免乱码问题
        // 调用 getParameter 之前，必须先设置编码
        // 设置请求体的字符集为UTF-8，从而解决post请求的中文乱码问题
        req.setCharacterEncoding("UTF-8");

        System.out.println(req.getParameter("username"));
        System.out.println(req.getParameter("passwd"));
        String[] insts = req.getParameterValues("inst");

        for (int i = 0; i <insts.length; i++) {
            System.out.println(insts[i]);
        }
    }
}
